package com.startit.csv;

import java.io.IOException;
import java.io.LineNumberReader;
import java.io.Reader;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.startit.csv.CSVField.DataType;
import com.startit.csv.exception.CSVReaderException;
import com.startit.csv.exception.TokenException;
import com.startit.csv.exception.ValidationException;

public abstract class CSVAbstractReader<T> implements ICSVReader {
	
	protected Reader reader;
	protected CSVFormat format;
	protected LineNumberReader lnr;

	public CSVAbstractReader(Reader reader, CSVFormat format) {
		super();
		this.reader = reader;
		this.lnr = new LineNumberReader(this.reader);
		this.format = format;
	}

	protected String[] readLineToStringArray() throws IOException, TokenException, ValidationException {
		String[] r = new String[format.getFieldsSize()];
		String line = this.lnr.readLine();
		if (line == null)
			return null;
		Tokenizer t = new Tokenizer(line, format.getDelimeter(),
				format.getQuote());
		String s = t.nextToken();
		int i = 0;
		List<CSVField> fields = format.getFields();
		while (s != null) {
			CSVField f = fields.get(i);
			f.setValue(s);
			r[i++] = f.getValue();
			s = t.nextToken();
		}		
		return r;
	}
	
	public abstract <T> T readLine() throws IOException, TokenException, ValidationException, CSVReaderException;

	public Reader getReader() {
		return reader;
	}

	public void setReader(Reader reader) {
		this.reader = reader;
	}

	public CSVFormat getFormat() {
		return format;
	}

	public void setFormat(CSVFormat format) {
		this.format = format;
	}

}
